<template>
  <div class="file-list-container">
    <el-card class="header-card">
      <div class="header-content">
        <el-button type="primary" icon="Back" @click="goBack">返回知识库</el-button>
        <div class="knowbase-info">
          <h2>知识库：{{ knowbaseName }}</h2>
          <div class="knowbase-id">ID: {{ knowbaseId }}</div>
        </div>
      </div>
    </el-card>

    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="文档名称">
          <el-input v-model="searchForm.keyword" placeholder="请输入文档名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="toolbar">
        <el-upload action="#" :show-file-list="false" :before-upload="beforeUpload" :http-request="handleUpload"
          :on-progress="handleUploadProgress">
          <el-button type="primary" icon="Upload">上传文档</el-button>
          <template #tip>
            <div class="upload-tip">支持上传不超过100MB的文件</div>
          </template>
        </el-upload>

        <el-progress v-if="uploadProgress > 0" :percentage="uploadProgress" status="success" class="upload-progress" />
      </div>

      <el-table :data="tableData" v-loading="loading">
        <el-table-column prop="file_name" label="文档名称" min-width="200" />
        <el-table-column prop="create_date" label="创建时间" min-width="100">
          <template #default="{ row }">
            {{ formatDate(row.create_date) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="330" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="viewImage(row)">查看图片</el-button>
            <el-button type="primary" size="small" @click="viewText(row)">查看文本</el-button>
            <el-button type="warning" size="small" @click="startParsingHandler(row)">开始解析</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handlePageChange" />
      </div>
    </el-card>

    <!--解析进度弹窗-->
     <el-dialog 
      v-model="parseDialogVisible" 
      title="文件解析进度" 
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <div class="parse-progress">
        <div class="progress-item">
          <span class="label">文字解析:</span>
          <el-progress 
            :percentage="textProgress" 
            status="success" 
            :text-inside="true" 
            :stroke-width="20"
          />
          <span class="count">{{ textCount }} 字符</span>
        </div>
        
        <div class="progress-item">
          <span class="label">图片提取:</span>
          <el-progress 
            :percentage="imageProgress" 
            status="warning" 
            :text-inside="true" 
            :stroke-width="20"
          />
          <span class="count">{{ imageCount }} 张图片</span>
        </div>
        
        <div class="progress-item">
          <span class="label">表格解析:</span>
          <el-progress 
            :percentage="tableProgress" 
            status="exception" 
            :text-inside="true" 
            :stroke-width="20"
          />
          <span class="count">{{ tableCount }} 个表格</span>
        </div>
      </div>
      
      <template #footer>
        <el-button 
          v-if="parseComplete" 
          type="primary" 
          @click="closeParseDialog"
        >
          完成
        </el-button>
        <el-button 
          v-else 
          :disabled="cancelling" 
          @click="cancelParse"
        >
          {{ cancelling ? '取消中...' : '取消解析' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted ,onUnmounted} from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFileList, deleteFile, uploadFile, startParsing } from '@/api/file'

const route = useRoute()
const router = useRouter()

// 从路由参数中获取知识库ID和名称
const knowbaseId = ref(route.params.knowbaseId)
const knowbaseName = ref(route.params.knowbaseName || '未知知识库')

// 搜索表单
const searchForm = reactive({
  keyword: '',
  knowbase_id: knowbaseId.value // 将知识库ID作为搜索条件
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})



// 解析相关状态
const parseDialogVisible = ref(false)
const textProgress = ref(0)
const textCount = ref(0)
const imageProgress = ref(0)
const imageCount = ref(0)
const tableProgress = ref(0)
const tableCount = ref(0)
const parseComplete = ref(false)
const cancelling = ref(false)
const currentParsingFileId = ref(null)
let eventSource = null

// 加载数据
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      page_size: pagination.pageSize
    }
    const response = await getFileList(params)
    const data = response.data.data
    tableData.value = data.list
    pagination.total = data.total_items
  } catch (error) {
    ElMessage.error('获取文档列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 日期格式化
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  pagination.page = 1
  fetchData()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchData()
}

// 页码改变
const handlePageChange = (page) => {
  pagination.page = page
  fetchData()
}

// 删除文档
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除文档 "${row.file_name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFile(row.file_id)
      ElMessage.success('删除成功')
      fetchData()
    } catch (error) {
      ElMessage.error('删除失败：' + error.message)
    }
  }).catch(() => { })
}

// 上传前处理 - 修改为100MB限制
const beforeUpload = (file) => {
  const isLt100M = file.size / 1024 / 1024 < 100 // 100MB限制
  if (!isLt100M) {
    ElMessage.error('文件大小不能超过100MB')
    return false
  }
  return true
}

// 处理上传
const uploadProgress = ref(0)

const handleUploadProgress = (event) => {
  if (event.total > 0) {
    uploadProgress.value = Math.round((event.loaded * 100) / event.total)
  }
}

const handleUpload = async (options) => {
  uploadProgress.value = 0 // 重置进度

  // const formData = new FormData()
  // formData.append('file', options.file)

  try {
    await uploadFile(knowbaseName.value, knowbaseId.value, options.file, {
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total > 0) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          )
          uploadProgress.value = percentCompleted
        }
      }
    })
    ElMessage.success('上传成功')
    fetchData()
  } catch (error) {
    ElMessage.error('上传失败：' + error.message)
  } finally {
    setTimeout(() => {
      uploadProgress.value = 0
    }, 2000)
  }
}

// 查看图片（暂未实现）
const viewImage = (row) => {

  ElMessage.info('查看图片：' + row.file_name)
  router.push({
    name: 'ImageView',
    params: {
      file_id: row.file_id //传递文件ID作为参数
    },
    query: {
      file_name:row.file_name
    }
  }
    
  )
}

// 查看文本（暂未实现）
const viewText = (row) => {
  router.push({
    name: 'TextView',
    params: { 
      file_id: row.file_id 
    },
    query: { 
      file_name: row.file_name 
    }
  })
}


//开始解析
const startParsingHandler = async (row) => {
  currentParsingFileId.value = row.file_id

  //重置进度状态
  resetProgress()

  //打开弹窗
  parseDialogVisible.value = true

  try {

    const requestData = {
      file_id: row.file_id,
      file_path: row.file_path,
      file_name: row.file_name,
      knowbase_id: knowbaseId.value
    }

    // 启动解析任务 - 调用新的POST接口
    const response = await startParsing(requestData); // 这个函数需要修改（见下文）
    const taskId = response.data.task_id; // 从响应中获取后端生成的任务ID
    currentParsingFileId.value = taskId; // 存储当前任务ID


    //创建SSE连接监听进度
    eventSource = new EventSource(`${import.meta.env.VITE_API_BASE_URL || '/api'}/file/parse/process/${taskId}`)

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data)
      updateProgress(data)
    }

    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error)
      if (eventSource.readyState === EventSource.CLOSED) {
        ElMessage.warning('解析进度连接已关闭')
      }
    }

  }
  catch (error) {
    ElMessage.error('开始解析失败: ' + error.message)
    parseDialogVisible.value = false
  }
}


// 更新进度显示
const updateProgress = (data) => {
  if (data.type === 'text') {
    textProgress.value = Number(data.percentage)
    textCount.value = Number(data.count)
  } else if (data.type === 'image') {
    imageProgress.value = Number(data.percentage)
    imageCount.value = Number(data.count)
  } else if (data.type === 'table') {
    tableProgress.value = Number(data.percentage)
    tableCount.value = Number(data.count)
  } else if (data.type === 'complete') {
    parseComplete.value = true
    if (eventSource) {
      eventSource.close()
    }
    ElMessage.success('文件解析完成')
  } else if (data.type === 'error') {
    ElMessage.error('解析错误: ' + data.message)
    parseDialogVisible.value = false
    if (eventSource) {
      eventSource.close()
    }
  }
}


// 重置进度状态
const resetProgress = () => {
  textProgress.value = 0
  textCount.value = 0
  imageProgress.value = 0
  imageCount.value = 0
  tableProgress.value = 0
  tableCount.value = 0
  parseComplete.value = false
  cancelling.value = false
}


// 关闭解析弹窗
const closeParseDialog = () => {
  parseDialogVisible.value = false
  if (eventSource) {
    eventSource.close()
  }
}


// 取消解析
const cancelParse = async () => {
  cancelling.value = true
  try {
    // 这里可以调用取消解析的API
    ElMessage.info('解析已取消')
    parseDialogVisible.value = false
    if (eventSource) {
      eventSource.close()
    }
  } catch (error) {
    ElMessage.error('取消解析失败: ' + error.message)
  } finally {
    cancelling.value = false
  }
}


// 返回知识库管理
const goBack = () => {
  router.push({ name: 'KnowledgeBase' })
}


// 组件卸载时关闭SSE连接
onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
  }
})

// 初始化加载
onMounted(() => {
  fetchData()
})
</script>

<style lang="scss" scoped>
.file-list-container {
  padding: 10px;

  .header-card {
    margin-bottom: 20px;

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .knowbase-info {
        text-align: right;

        h2 {
          margin: 0;
          font-size: 18px;
        }

        .knowbase-id {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .toolbar {
      margin-bottom: 15px;
      display: flex;
      align-items: center;

      .upload-tip {
        margin-left: 10px;
        font-size: 12px;
        color: #999;
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .upload-progress {
    margin-top: 10px;
  }

  .parse-progress {
    padding: 10px 0;
  }
  
  .progress-item {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    .label {
      width: 80px;
      font-weight: bold;
    }
    
    .el-progress {
      flex: 1;
      margin: 0 15px;
    }
    
    .count {
      width: 80px;
      text-align: right;
      color: #666;
      font-size: 12px;
    }
  }
}
</style>